package edu.dublbo.generator.auth.controller;

import edu.dublbo.generator.auth.model.TAuthUser;
import edu.dublbo.generator.auth.service.AuthUserService;
import edu.dublbo.generator.common.exception.BaseException;
import edu.dublbo.generator.common.exception.OptErrorException;
import edu.dublbo.generator.common.result.OptStatus;
import edu.dublbo.generator.common.result.ResponseResult;
import edu.dublbo.generator.common.result.Result;
import edu.dublbo.generator.common.utils.SnowflakeIdWorker;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotBlank;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 权限用户控制类
 *
 * @author Administrator
 * @since 2020/9/12 17:13,星期六
 * Always believe that something wonderful is about to happen.
 **/
@RestController
@RequestMapping(value = "/auth/user")
public class AuthUserController {
    public static final Logger logger = LoggerFactory.getLogger(AuthUserController.class);

    @Autowired
    private AuthUserService service;

    @Autowired
    private SnowflakeIdWorker idWorker;

    // 用户登录
    @PostMapping("/login")
    public Result<Map<String, Object>> login(@NotBlank String username, @NotBlank String password) {
        // 验证用户名和密码，并生成响应的 token
        String token = service.valid(username, password);

        if (StringUtils.isBlank(token)) {
            throw new OptErrorException(OptStatus.FAIL.getOptCode(), "授权失败");
        }

        Map<String, Object> map = new HashMap<>();
        map.put("token", "Bearer:" + token);
        return ResponseResult.generateSuccessResult(map);
    }

    // 增加权限用户
    @PostMapping
    public TAuthUser add(@Validated TAuthUser entity, HttpServletRequest request) {
        // 主键生成策略，可自定义
//        String id = UUID.randomUUID().toString().replace("-","");
        String id = idWorker.nextStringId();
        logger.info("Generate id is : {}", id);
        entity.setId(id);
        entity.setCreateTime(new Date());
        entity.setModifyTime(entity.getCreateTime());
        // 这里的用户可以自定义，默认为 admin
        entity.setCreateUser("admin");
        entity.setModifyUser("admin");
        entity.setDeleteFlag(0);
        service.save(entity);
        return entity;
    }

    // 修改权限用户
    @PutMapping(value = "/{id}")
    public TAuthUser edit(@PathVariable(value = "id") String id, @RequestBody TAuthUser modifyEntity, HttpServletRequest request) {
        TAuthUser oldEntity = service.get(id);
        if (oldEntity != null) {
            // 这里需根据业务需求修改哪些字段，
            // 但是 id,createUser,createTime,modifyUser,modifyTime,deleteFlag 这些字段不允许用户修改
            // oldEntity 为修改前的对象，modifyEntity 为修改后的对象，该怎么做自己根据业务需求自己定制吧，这里就不生成了
            // Do what you want to do
            modifyEntity.setId(id);
            modifyEntity.setModifyTime(new Date());
            modifyEntity.setModifyUser("admin");
            service.update(modifyEntity);
        }
        return modifyEntity;
    }

    // 获取权限用户的基本信息
    @GetMapping(value = "/{id}")
    public TAuthUser detail(@PathVariable(value = "id") String id) {
        TAuthUser entity = service.get(id);
        return entity;
    }

    // 删除权限用户
    @DeleteMapping(value = "/{id}")
    public TAuthUser delete(@PathVariable(value = "id") String id) {
        TAuthUser entity = service.get(id);
        entity.setModifyUser("admin");
        entity.setModifyTime(new Date());
        entity.setDeleteFlag(1);
        service.update(entity);
        return entity;
    }
}
